package com.zzyl.job;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.zzyl.constant.CacheConstants;
import com.zzyl.dto.AlertNotifyDto;
import com.zzyl.entity.AlertData;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertDataMapper;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.mapper.DeviceMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.vo.DeviceDataVo;
import com.zzyl.ws.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 设备上报数据报警规则过滤
 */
@Slf4j
@Component
public class AlertJob {
    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private AlertDataMapper alertDataMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 定时任务：检测设备上报数据
     */
    @Scheduled(cron = "0/20 * * * * ?")
    public void deviceDataAlertFilter() {
        log.info("定时任务：检测设备上报数据");
        //1.查询所有报警规则，如果为空，程序结束
        List<AlertRule> allAlertRules = alertRuleMapper.selectAll();
        if (CollUtil.isEmpty(allAlertRules)) {
            return;
        }

        //2.查询所有设备最新上报数据，如果为空，程序结束
        List<Object> jsonStrList = stringRedisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        if (CollUtil.isEmpty(jsonStrList)) {
            return;
        }
        //3.设备上报数据不为空，提取设备上报数据为list
        List<DeviceDataVo> deviceDataVoList = new ArrayList<>();
        jsonStrList.forEach(json -> {
            CollUtil.addAll(deviceDataVoList, JSON.parseArray(json.toString(), DeviceDataVo.class));
        });
        //4.对每一条设备上报数据进行报警规则校验
        deviceDataVoList.forEach(deviceDataVo -> {
            alertFilter(deviceDataVo);
        });
    }

    /**
     * 校验设备上报数据，进行报警规则过滤处理
     *
     * @param deviceDataVo 设备上报数据
     */
    private void alertFilter(DeviceDataVo deviceDataVo) {
        //获取设备上报数据时间，如果上报发生在1分钟前，为历史数据，不再处理
        if (LocalDateTime.now().plusMinutes(-1).isAfter(deviceDataVo.getAlarmTime())) {
            return;
        }
        //查询报警规则，将对于全部设备的报警规则 和 对于本设备的报警规则合并
        List<AlertRule> theDeviceAlertRules = alertRuleMapper.selectByFunctionId(deviceDataVo.getFunctionId(),
                deviceDataVo.getIotId(), deviceDataVo.getProductKey());
        List<AlertRule> allDeviceAlertRules = alertRuleMapper.selectByFunctionId(deviceDataVo.getFunctionId(),
                "-1", deviceDataVo.getProductKey());
        Collection<AlertRule> alertRules = CollUtil.addAll(theDeviceAlertRules, allDeviceAlertRules);

        //如果报警规则为空，程序结束
        if (CollUtil.isEmpty(alertRules)) {
            return;
        }
        //如果报警规则不为空，遍历报警规则，进行校验
        alertRules.forEach(alertRule -> deviceDateAlarmHandler(deviceDataVo, alertRule));
    }

    /**
     * 设备数据报警处理器
     *
     * @param deviceDataVo 设备上报数据
     * @param alertRule    报警规则
     */
    private void deviceDateAlarmHandler(DeviceDataVo deviceDataVo, AlertRule alertRule) {
        //第一层校验：判断数据上报时间是否在规则生效时段内
        LocalTime startTime = LocalTime.parse(alertRule.getAlertEffectivePeriod().split("~")[0]);
        LocalTime endTime = LocalTime.parse(alertRule.getAlertEffectivePeriod().split("~")[1]);

        //上报时间
        LocalTime alertTime = deviceDataVo.getAlarmTime().toLocalTime();

        //如果上报时间不在生效时间段内，校验结束
        if (alertTime.isBefore(startTime) || alertTime.isAfter(endTime)) {
            return;
        }


        //第二层校验：判断设备数据值是否触发规则阈值
        String operator = alertRule.getOperator();
        Double deviceValue = Double.valueOf(deviceDataVo.getDataValue());
        Double ruleValue = Double.valueOf(alertRule.getValue());

        //将两个值比较大小
        int compare = deviceValue.compareTo(ruleValue);
        //如果设备值比规则值大，并且运算符为大于；或者设置值比规则值小，并且运算符为小于，则触发阈值
        if ((compare >= 0 && StrUtil.equals(">=", operator))
                || (compare < 0 && StrUtil.equals("<", operator))) {
            //说明设备数据触发了规则的阈值
            log.info("说明设备数据触发了规则的阈值:{} {}", alertRule, deviceDataVo);
        } else {
            //正常数据，不需要处理
            return;
        }

        //第三层校验：校验当前设备+功能的报警规则是否处于沉默周期
        //如果redis中存在对应沉默周期数据，则当前设备+功能正处于沉默周期，无需报警
        String silentCycleRedisKey = CacheConstants.ALERT_SILENT_CYCLE +
                deviceDataVo.getIotId() + deviceDataVo.getFunctionId() + alertRule.getId();
        //去redis中查询，是否存在指定的key
        Boolean hasKey = stringRedisTemplate.hasKey(silentCycleRedisKey);
        if (hasKey) {
            //保持沉默，不需要处理
            return;
        }

        //第四层校验：判断持续周期
        String triggerCountRedisKey = CacheConstants.ALERT_TRIGGER_COUNT +
                deviceDataVo.getIotId() + deviceDataVo.getFunctionId() + alertRule.getId();
        //去redis中查询值
        String count = stringRedisTemplate.opsForValue().get(triggerCountRedisKey);
        //如果count为空，当作0看待
        count = StrUtil.nullToDefault(count, "0");

        int triggerCount = Integer.valueOf(count) + 1;

        //和规则的持续周期比较
        if (triggerCount < alertRule.getDuration()) {
            //说明还不满足持续周期，将数值存入redis
            stringRedisTemplate.opsForValue().set(triggerCountRedisKey, String.valueOf(triggerCount));
            return;
        }

        ///////////////////////  报警逻辑处理
        log.error("已检测到设备数据满足报警条件:{} {}", alertRule, deviceDataVo);

        /*
            报警需要做的事情：
                1)添加沉默周期，时效性
                2)删除持续周期
                3)先查询通知人，添加报警数据
                4)发送ws消息
         */
        //1)添加沉默周期，时效性
        stringRedisTemplate.opsForValue().set(silentCycleRedisKey,
                "true",
                alertRule.getAlertSilentPeriod(),
                TimeUnit.MINUTES);
        //2)删除持续周期
        stringRedisTemplate.delete(triggerCountRedisKey);
        //3)先查询通知人，添加报警数据       3个SQL：随身设备、床位、房间
        //判断设备绑定位置
        Integer physicalLocationType = deviceDataVo.getPhysicalLocationType(); //1房间 2床位 -1老人

        List<Long> userIds = null;

        if (ObjectUtil.equals(physicalLocationType, 1)) {//1房间   固定设备
            userIds = userRoleMapper.selectUserIdsByRoleName("维修工");
        }

        if (ObjectUtil.equals(physicalLocationType, 2)) {//2床位    固定设备
            userIds = deviceMapper.selectNursingIdsByIotIdWithBed(deviceDataVo.getIotId());
        }

        if (ObjectUtil.equals(physicalLocationType, -1)) {//-1老人    随身设备
            userIds = deviceMapper.selectNursingIdsByIotIdWithElder(deviceDataVo.getIotId());
        }

        //查询管理员
        List<Long> adminIds = userRoleMapper.selectUserIdsByRoleName("超级管理员");

        //最终通知的用户id集合
        Collection<Long> allUserIds = CollUtil.addAll(userIds, adminIds);

        if (CollUtil.isEmpty(allUserIds)) {
            return;
        }

        //添加报警数据
        insertAlertData(allUserIds, deviceDataVo, alertRule);

        //4)发送ws消息
        sendWebSocketMessage(allUserIds, deviceDataVo, alertRule);
    }

    /**
     * 给指定人员发送ws消息
     *
     * @param allUserIds
     * @param deviceDataVo
     * @param alertRule
     */
    private void sendWebSocketMessage(Collection<Long> allUserIds, DeviceDataVo deviceDataVo, AlertRule alertRule) {

        //创建报警通知消息对象
        AlertNotifyDto alertNotifyDto = AlertNotifyDto.builder().build();

        BeanUtil.copyProperties(alertRule, alertNotifyDto);
        BeanUtil.copyProperties(deviceDataVo, alertNotifyDto);

        //设置语音
        alertNotifyDto.setVoiceNotifyStatus(1);
        alertNotifyDto.setNotifyType(1);
        alertNotifyDto.setIsAllConsumer(false);
        //alertNotifyDto.setId(1L);


        webSocketServer.sendMessageToConsumer(alertNotifyDto, new ArrayList<>(allUserIds));
    }

    private void insertAlertData(Collection<Long> allUserIds, DeviceDataVo deviceDataVo, AlertRule alertRule) {
        //遍历用户集合，给每个用户添加报警数据
        allUserIds.forEach(userId -> {
            AlertData alertData = new AlertData();

            BeanUtil.copyProperties(alertRule, alertData);
            BeanUtil.copyProperties(deviceDataVo, alertData);

            alertData.setAlertRuleId(alertRule.getId()); //报警规则id

            String alertReason = String.format("%s %s %s, 持续周期 %s 次触发报警!",
                    alertRule.getFunctionName(),
                    alertRule.getOperator(),
                    alertRule.getValue(),
                    alertRule.getDuration());

            alertData.setAlertReason(alertReason); //报警原因
            alertData.setType(alertRule.getAlertDataType());//报警数据类型
            alertData.setStatus(0);//0待处理
            alertData.setUserId(userId);//接收人id
            alertData.setDeviceDescription(deviceDataVo.getRemark());

            alertDataMapper.insert(alertData);
        });

    }

}